package com.zyd.blog.core.shiro;


import com.zyd.blog.homeart.util.ResponseObject;
import com.zyd.blog.personal.service.LoginService;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

//@Component
public class TokenFilter extends BasicHttpAuthenticationFilter {

    @Resource
    private LoginService loginService;
    /**
     * 对请求头进行拦截，如果没有token则直接返回错误信息
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
          HttpServletRequest req = (HttpServletRequest) request;
        Enumeration names = req.getHeaderNames();
        System.out.println("==============================验证请求头=====================================");
        System.out.println("===================================================================");
        while(names.hasMoreElements()){
            String name = (String) names.nextElement();
            System.out.println(name + ":" + req.getHeader(name));
        }
        System.out.println("===================================================================");
        String token=req.getHeader("token");
        if(!StringUtils.isEmpty(token)){
            ResponseObject responseObject = loginService.checkToken(token);
            if(responseObject.getCode()==0){//token正确
               return  true;
            }
        }
        return false;
    }
}
